/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) {
            return 0;
        }
        int ans = numeric_limits<int>::min();
        dfs(root, ans);
        return ans;
    }

    int dfs(TreeNode *root, int &ans) {
        if (root == NULL) {
            return 0;
        }
        int left = dfs(root->left, ans);
        int right = dfs(root->right, ans);
        int ret = root->val;
        if (left > right) {
            if (left > 0) {
                ret += left;
            }
        } else {
            if (right > 0) {
                ret += right;
            }
        }
        int sum = root->val;
        if (left > 0) {
            sum += left;
        }
        if (right > 0) {
            sum += right;
        }
        ans = max(ans, sum);
        return ret;
    }
};
